package com.lele.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lele.pojo.Book;

import com.lele.util.*;


@WebServlet("/login")
public class login extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("UTF-8");
		String username=request.getParameter("username");
        String password=request.getParameter("password");
        System.out.println("user:"+username+"----"+password);
        Connection conn=null;
        PreparedStatement st = null;
        ResultSet resultSet=null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            conn= JDBCUtils.getConnection();
            String sql="select * from student where username=? and password=?";
            st = conn.prepareStatement(sql);
            st.setString(1,username);
            st.setString(2,password);
            resultSet = st.executeQuery();
            if(resultSet.next()) {
            	System.out.println(resultSet.getString(1)+"---"+resultSet.getString(2));
            	System.out.println(username+"登录成功");
//            	map.put("userExsit",true);
//            	map.put("msg", username+" success to login!");
//            	//将map转为json
//                ObjectMapper mapper = new ObjectMapper();
//                //并且传递给客户端
//                mapper.writeValue(response.getWriter(),map);
            	response.getWriter().write("true");
                System.out.println(map);
                return;
            }
            System.out.println("登陆失败");
            response.getWriter().write("false");
        } catch (SQLException throwables) {
        	
            throwables.printStackTrace();
        }
        finally {
            JDBCUtils.close(resultSet,st,conn);
        }
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
